package nio;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/25 17:16
 */
public class NonBlockingNIOTest2 {
    public static void main(String[] args) {
        try (DatagramChannel channel = DatagramChannel.open()) {
            //切换成非阻塞模式
            channel.configureBlocking(false);

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            System.out.println("input(q:exit):");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String msg = scanner.nextLine();
                if ("q".equalsIgnoreCase(msg)) {
                    break;
                }
                buffer.put(msg.getBytes());
                buffer.flip();
                channel.send(buffer, new InetSocketAddress("127.0.0.1", 9898));
                buffer.clear();
                System.out.println("send msg over");
                System.out.println("input(q:exit):");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testServer() {
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(9898));
            Selector selector = Selector.open();

            channel.register(selector, SelectionKey.OP_READ);

            while (selector.select() > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();

                    if (key.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);

                        int len = 0;
                        StringBuilder builder = new StringBuilder();
                        while ((len = channel.read(buffer)) > 0) {
                            buffer.flip();
                            builder.append(new String(buffer.array(), 0, len));
                            buffer.clear();
                        }
                        if (StringUtils.isNoneEmpty(builder)) {
                            System.out.println(builder);
                        }
                    }
                    iterator.remove();
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
